package com.ebt.m.proposal_v2.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.widgets.view.EBTDialog;
import com.ebt.m.customer.view.ConfirmDialog;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.EbtEqualUtil;
import com.ebt.m.proposal_v2.adapter.ProductInProposalAdapter;
import com.ebt.m.proposal_v2.adapter.ProductInProposalAdapter2;
import com.ebt.m.proposal_v2.base.Constant;
import com.ebt.m.proposal_v2.bean.ApplicantEntity;
import com.ebt.m.proposal_v2.bean.ArgProposalDetail;
import com.ebt.m.proposal_v2.bean.ArgProposalMake;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.bean.ProposalEntity;
import com.ebt.m.proposal_v2.bean.event.DraftUpdateCompleteEvent;
import com.ebt.m.proposal_v2.bean.event.ExemptCompleteEvent;
import com.ebt.m.proposal_v2.bean.event.ExemptResetEvent;
import com.ebt.m.proposal_v2.bean.event.MainChooseEvent;
import com.ebt.m.proposal_v2.bean.event.UpdaterFailEvent;
import com.ebt.m.proposal_v2.dao.request.ParamGetAttaches;
import com.ebt.m.proposal_v2.dao.request.ParamGetRisks;
import com.ebt.m.proposal_v2.dao.response.BusinessConfig;
import com.ebt.m.proposal_v2.dao.response.ResponseChanShuoItem;
import com.ebt.m.proposal_v2.dao.response.ResponseTouDan;
import com.ebt.m.proposal_v2.dao.response.TouDanInfo;
import com.ebt.m.proposal_v2.event.AddAttachProductEvent;
import com.ebt.m.proposal_v2.event.AddMoreInsuredEvent;
import com.ebt.m.proposal_v2.event.ApplicantChangedEvent;
import com.ebt.m.proposal_v2.event.CancelCalculating;
import com.ebt.m.proposal_v2.event.DeleteMoreInsuredEvent;
import com.ebt.m.proposal_v2.event.InsuredChangedEvent;
import com.ebt.m.proposal_v2.event.ProductChangedEvent;
import com.ebt.m.proposal_v2.event.ProductsChangedEvent;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.proposal_v2.mvp.base.MVPCompatActivity;
import com.ebt.m.proposal_v2.mvp.contract.ProposalMakeContract;
import com.ebt.m.proposal_v2.mvp.presenter.ProposalMakePresenter;
import com.ebt.m.proposal_v2.retrofit.ResponseBodyBase;
import com.ebt.m.proposal_v2.ui.function.ExemptDao;
import com.ebt.m.proposal_v2.ui.function.InsuranceCellViewUpdater;
import com.ebt.m.proposal_v2.ui.view.ApplicantView;
import com.ebt.m.proposal_v2.ui.view.InsuranceView;
import com.ebt.m.proposal_v2.ui.view.InsuredAndInsuranceView;
import com.ebt.m.proposal_v2.ui.view.InsuredView;
import com.ebt.m.proposal_v2.ui.view.MoreInsuredView;
import com.ebt.m.proposal_v2.utils.ArrayUtils;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.proposal_v2.utils.EBTDataFormat;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.proposal_v2.utils.Utils;
import com.ebt.m.proposal_v2.widget.common.TopBar;
import com.ebt.m.proposal_v2.widget.dialog.AdditionalRiskChooseDialog;
import com.ebt.m.proposal_v2.widget.dialog.EBTBottomAdapterDialog;
import com.ebt.m.proposal_v2.widget.dialog.EBTConfirmDialogWithTitle;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.proposal_v2.widget.view.CompoundTextView;
import com.ebt.m.proposal_v2.widget.view.EnableButton;
import com.ebt.m.proposal_v2.widget.view.InsuranceCellView;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.imageloader.ImageLoader;
import com.ebt.m.utils.imageloader.ImageLoaderUtil;
import com.ebt.m.widget.ActSingleImgViewer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.ebt.m.proposal_v2.ProposalConstant.ACTION_PRODUCT_ADD;
import static com.ebt.m.proposal_v2.ProposalConstant.ACTION_PRODUCT_DELETE;
import static com.ebt.m.proposal_v2.ProposalConstant.ACTION_PRODUCT_EDIT;
import static com.ebt.m.proposal_v2.ProposalConstant.PRODUCT_ATTATCH;
import static com.ebt.m.proposal_v2.ProposalConstant.PRODUCT_MAIN;
import static com.ebt.m.proposal_v2.ProposalConstant.RISK_TYPE_COMMON;
import static com.ebt.m.proposal_v2.ProposalConstant.RISK_TYPE_EXEMPT;

public class MakeProposalActivity extends MVPCompatActivity<ProposalMakePresenter> implements ProposalMakeContract.View {

    public static final String Arg = "param";
    public static final int Flag_Default = 0; // 默认创建
    public static final int Flag_Draft = 1; // 草稿新建
    public static final int Flag_Customer = 2; // 客户新建
    public static final int Flag_Product = 3; // 产品新建
    public static final int Flag_Dynamic = 4; // 动态新建

    @BindView(R.id.proposal_make_topBar)
    TopBar mTopBar;
    @BindView(R.id.proposal_make_applicant)
    ApplicantView mApplicantView;
    @BindView(R.id.proposal_make_insured)
    InsuredView mInsuredView;
    @BindView(R.id.proposal_make_insurance)
    InsuranceView mInsuranceView;
    @BindView(R.id.proposal_make_totalPremium)
    TextView mInsuranceAmountTotal;
    @BindView(R.id.proposal_make_submit)
    EnableButton mActionMakeProposal;
    @BindView(R.id.proposal_online_toudan)
    EnableButton mActionOnlineToudan;
    @BindView(R.id.proposal_make_productInfo)
    CompoundTextView mTextProductInfo;
    @BindView(R.id.proposal_make_product_line)
    View mProductSeparator;
    @BindView(R.id.proposal_make_scroll)
    ScrollView mScrollView;
    @BindView(R.id.proposal_make_bottomBar)
    LinearLayout mBottomBar;
    @BindView(R.id.more_insure_view)
    MoreInsuredView moreInsuredView;
    @BindView(R.id.empty)
    View mEmptyView;
    @BindView(R.id.product_empty_content)
    TextView mEmptyContent;
    @BindView(R.id.empty_container)
    LinearLayout mEmptyContentContainer;
    @BindView(R.id.no_net_container)
    RelativeLayout noNetContainer;
    @BindView(R.id.net_slow_container)
    RelativeLayout netSlowContainer;
    @BindView(R.id.load_refresh)
    TextView loadRefresh;
    @BindView(R.id.load_refresh_net)
    TextView loadRefreshNet;

    @BindView(R.id.more_insure_view_container)
    LinearLayout moreInsuredAndInsuranceViewContainer;

    private ArgProposalMake mArg;
    private EBTProgressDialog mProgressDialog;
    private EBTBottomAdapterDialog<ProductInProposalAdapter> mDialogProductInProposal;
    private boolean isCreateNewProposal = true; // 是否是不带任何信息的新建计划书
    private String originCustomerName; // 更新客户，保持客户名称不变；该字段保存客户原有姓名
    private ExemptDao mExemptDao; // 用于处理豁免险模块
    private boolean isProposalDraft; // 是否是来自草稿编辑
    private boolean isProposalDraftSaving; // 是否正在保存草稿，防止保存期间多次点击形成多个重复草稿


    public static final String Finish_To_Proposal_List = "Finish_To_Proposal_List";
    private boolean finishToProposalList = false;

    private ProposalEntity orgProposalEntity;//用于存储由草稿获取的信息

    @Override
    public void initArguments() {
        Bundle extra = getIntent().getExtras();
        finishToProposalList = getIntent().getBooleanExtra(Finish_To_Proposal_List, false);
        if (extra != null) {
            mArg = (ArgProposalMake) extra.getSerializable(Arg);
        }
    }

    @Override
    public void setEmptyView(boolean isEmpty) {

    }

    @Override
    protected ProposalMakePresenter createPresenter() {
        return new ProposalMakePresenter(getApplicationContext(), this);
    }

    @Override
    protected int setContentResource() {
        return R.layout.activity_make_proposal;
    }

    @Override
    protected void onActivityCreate() {
        initArguments();
        checkProposalMakeAllowed();
        initSideBar();
        initApplicantView();
        initInsuredView();
        initInsuranceViews();
        EventBus.getDefault().register(this);
        if (!isCreateNewProposal) {
            mApplicantView.hideTipView();
        }

        mExemptDao = new ExemptDao(this, mInsuranceView);

        mApplicantView.setCorrespondingInsuredView(mInsuredView);
        mInsuredView.setCorrespondingInsuranceView(mInsuranceView);
        mInsuredView.setCorrespondingApplicantView(mApplicantView);
        mInsuranceView.setCorrespondingApplicantView(mApplicantView);
        mInsuranceView.setCorrespondingInsuredView(mInsuredView);

        mInsuredView.setRelationByCode(0);
        //默认新建不需要联网判断
        if (NetUtils.isNetworkConnected(this) || (mArg != null && mArg.flag == Flag_Default)) {
            initByFlag();
        } else {
            showToast(getResources().getString(R.string.network_fail));
            showEmpty(false, true, false);
        }

        mActionOnlineToudan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = (String) mActionOnlineToudan.getTag();
                if (!TextUtils.isEmpty(url)) {
                    Intent webIntent = new Intent(MakeProposalActivity.this, WebBaseActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, "在线投单");
                    bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4NEW_BASE);
                    bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, true);
                    bundle.putString(WebBaseActivity.WEB_TYPE_LINK, url);
                    webIntent.putExtras(bundle);
                    startActivity(webIntent);
                }
            }
        });
    }

    @Override
    protected void onActivityDestroy() {
        Utils.print("draft", "MakeProposalActivity destroy");
        EventBus.getDefault().unregister(this);
        if (mExemptDao != null) {
            mExemptDao.destroyView();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        cancelProgress();
        if (mDialogProductInProposal != null && mDialogProductInProposal.isVisible()) {
            mDialogProductInProposal.dismiss();
        }
    }

    @Override
    public void initByFlag() {
        if (mArg == null) {
            return;
        }
        switch (mArg.flag) {
            case Flag_Default: // 创建
                break;
            case Flag_Draft: // 草稿
                initWithDraft();
                break;
            case Flag_Customer: // 客户
                initWithCustomer();
                break;
            case Flag_Product:
                initWithProduct(); // 产品
                break;
            case Flag_Dynamic:
                initWithDynamic(); // 首页
                break;
        }
    }

    @Override
    public void initWithDraft() {
        isCreateNewProposal = false;
        isProposalDraft = true;
        mPresenter.getProposalDraft(mArg.proposalId);
    }

    //TODO
    @Override
    public boolean checkDraftSame() {
        ProposalEntity temp = getProposal();
        if (EbtEqualUtil.proposalEntityEquals(temp, orgProposalEntity)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onDraftDownloadFinished() {
        ProposalEntity t = getProposal();
        orgProposalEntity = new ProposalEntity(t);
        updateToudanByProductId(t == null ? 0 : t.getMainRiskProductId());
    }

    @Override
    public void displayProductPropertiyImg(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        List<InsuranceCellView> cellViews = mInsuranceView.getInsuranceCellViews();
        if (cellViews != null && cellViews.size() > 0) {
            InsuranceCellView cellView = cellViews.get(0);
            View imgTipArea = cellView.findViewById(R.id.img_tip_area);
            if (imgTipArea != null) {
                imgTipArea.setVisibility(View.VISIBLE);
                ImageView imgTip = imgTipArea.findViewById(R.id.img_tip);
                if (imgTip == null) {
                    return;
                }
                ImageLoaderUtil.getInstance().loadImage(this, new ImageLoader.Builder().url(url).imgView(imgTip).build());
                imgTip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActSingleImgViewer.start(MakeProposalActivity.this, imgTip, url);
                    }
                });
            }
        }
    }

    @Override
    public void initWithCustomer() {
        isCreateNewProposal = false;
        if (!TextUtils.isEmpty(mArg.customerId)) {
            mPresenter.getCustomerDetail(mArg.customerId);
        }
        if (!TextUtils.isEmpty(mArg.productId)) {
            updateToudanByProductId(Integer.valueOf(mArg.productId));
        }
    }

    @Override
    public void initWithProduct() {
        isCreateNewProposal = false;
        mApplicantView.bindData(mArg.customer);
        mInsuredView.bindData(mArg.customer);

        updateInsurancePerson(mApplicantView.getApplicant(), mInsuredView.getInsured());

        if (!TextUtils.isEmpty(mArg.productId) && mArg.customer != null) {
            mPresenter.getProductDetail(mArg.product,
                    mArg.productId,
                    DataUtils.formatRequestParamAge(mArg.customer.getAge() + "", mArg.customer.getBirthday()),
                    mArg.customer.getSex(),
                    mArg.customer.getCareerCategory());
        }

        if (!TextUtils.isEmpty(mArg.productId)) {
            updateToudanByProductId(Integer.valueOf(mArg.productId));
        }
    }

    @Override
    public void initWithDynamic() {
        isCreateNewProposal = false;
        if (!TextUtils.isEmpty(mArg.productId)) {
            mPresenter.getDefaultMainProductDetails(mArg.productId);
        }
        if (!TextUtils.isEmpty(mArg.productId)) {
            updateToudanByProductId(Integer.valueOf(mArg.productId));
        }
    }

    @Override
    public void initPersonAfterProductGetted(Customer customer) {
        mApplicantView.bindData(customer);
        mInsuredView.bindData(customer);
        updateInsurancePerson(mApplicantView.getApplicant(), mInsuredView.getInsured());
    }

    @Override
    public void setDraftSaving(boolean saving) {
        isProposalDraftSaving = saving;
    }

    @Override
    public void showMoreInsuredView(boolean show) {
        if (show) {
            moreInsuredView.setVisibility(View.VISIBLE);
        } else {
            moreInsuredView.setVisibility(View.GONE);
        }
    }

    @Override
    public double[] getTotalPremiumAndCoverage() {
        /* 计算总保额与总保费*/
        List<InsuranceEntity> list = getListInsuranceEntities();
        if (list == null || list.size() == 0) {
            return new double[]{0, 0};
        }
        double mTotalPremium = 0;
        double mTotalCoverage = 0;
        for (InsuranceEntity ie : list) {
            if (ie != null && ie.isValidAccordingToInsuredEntityAndInsuranceEntity()) {
                try {
                    if (ie.premium != null) {
                        mTotalPremium += Double.valueOf(ie.premium.value);
                    }
                    if (ie.coverage != null) {
                        mTotalCoverage += Double.valueOf(ie.coverage.value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new double[]{mTotalPremium, mTotalCoverage};
    }

    private List<InsuranceEntity> getListInsuranceEntities() {
        List<InsuranceEntity> listAll = new ArrayList<>();
        List<InsuranceEntity> list = mInsuranceView.getProductsData();
        if (list != null) {
            listAll.addAll(list);
        }

        int childCount = moreInsuredAndInsuranceViewContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            InsuredAndInsuranceView iv = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(i);
            List<InsuranceEntity> entities = iv.getInsuranceEntities();
            if (entities != null) {
                listAll.addAll(entities);
            }
        }
        return listAll;
    }

    @Override
    public boolean checkBeforeMakeProposal(ProposalEntity proposalEntity) {
        boolean isApplicantCorrect = mApplicantView.check();
        if (!isApplicantCorrect) {
            return false;
        }
        boolean isRelationCorrect = mPresenter.checkRelation(-1, proposalEntity);
        if (!isRelationCorrect) {
            return false;
        }
        boolean isProductOptionCorrect = checkProductOption();
        return isProductOptionCorrect;
    }

    @Override
    public void setMakeProposalEnabled(boolean enabled) {
        mActionMakeProposal.setEnableState(enabled);
    }

    @Override
    public void updateApplicant(Customer customer, ApplicantEntity applicant) {
        if (customer != null) {
            mApplicantView.bindData(customer);
        } else {
            mApplicantView.bindData(applicant);
        }
    }

    @Override
    public void updateInsured(Customer customer, InsuredEntity insured) {
        if (customer != null) {
            mInsuredView.bindData(customer);
        } else {
            mInsuredView.bindData(insured);
        }
    }

    @Override
    public void updateOtherInsured(List<InsuredEntity> insuredEntities) {
        //从第二被保人算起，因此这里需要 > 1
        if (insuredEntities != null && insuredEntities.size() > 1) {
            //根据insuredEntities，添加view
            moreInsuredAndInsuranceViewContainer.setVisibility(View.VISIBLE);
            for (int i = 1; i < insuredEntities.size(); i++) {
                addAInsuredAndInsuranceViewByExistedData(insuredEntities.get(i));
            }
        }
        updateShowMoreInsureButton();
    }

    @Override
    public void updateShowMoreInsureButton() {
        if (canAddMore()) {
            showMoreInsuredView(true);
        } else {
            showMoreInsuredView(false);
        }
    }

    @Override
    public void updateBusinessConfig(BusinessConfig businessConfig) {
        mInsuredView.setBusinessConfig(businessConfig);
        if (moreInsuredAndInsuranceViewContainer != null && moreInsuredAndInsuranceViewContainer.getVisibility() == View.VISIBLE) {
            int count = moreInsuredAndInsuranceViewContainer.getChildCount();
            for (int i = 0; i < count; i++) {
                InsuredAndInsuranceView item = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(i);
                item.updateDefaultBusinessConfig(businessConfig);
            }
        }
    }

    private void addAInsuredAndInsuranceViewByExistedData(InsuredEntity entity) {
        InsuredAndInsuranceView insuredAndInsuranceView = new InsuredAndInsuranceView(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
        if (mainInsuranceEntity != null) {
            insuredAndInsuranceView.updateDefaultBusinessConfig(mainInsuranceEntity.getBusinessConfig());
        }
        moreInsuredAndInsuranceViewContainer.addView(insuredAndInsuranceView, lp);
        insuredAndInsuranceView.setOtherRelationCallBack(otherRelationCallBack);
        insuredAndInsuranceView.setCorrespondingApplicantView(mApplicantView);
        insuredAndInsuranceView.updateTitleByIndex(moreInsuredAndInsuranceViewContainer.getChildCount() - 1);
        insuredAndInsuranceView.updateContentByDraftEntity(entity);
    }

    private ArrayList<String> getMoreInsuredAdditionalIds() {
        try {
            int count = moreInsuredAndInsuranceViewContainer.getChildCount();
            if (count > 0 && moreInsuredAndInsuranceViewContainer.getChildAt(0) instanceof InsuredAndInsuranceView) {
                InsuredAndInsuranceView insuredAndInsuranceView = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(0);
                return insuredAndInsuranceView.getMoreInsuredAdditionalIds();
            }
        } catch (Exception e) {
            Logger.e(e);
        }
        return null;
    }

    @Override
    public void updateInsurancePerson(ApplicantEntity applicant, InsuredEntity insured) {
        if (mInsuranceView != null) {
            mInsuranceView.setApplicantPerson(applicant);
            mInsuranceView.setInsuredPerson(insured);
        }
    }

    @Override
    public boolean isProposalDraft() {
        return isProposalDraft;
    }

    @Override
    public void setTotalPremiumValue(String value) {
        mInsuranceAmountTotal.setText(value);
    }

    @Override
    public void addRiskViews(List<InsuranceEntity> list) {
        mInsuranceView.addRiskViews(list);
    }

    @Override
    public void allowSaveCustomer(boolean allow) {
        mApplicantView.setCustomerSave(allow);
    }

    @Override
    public void initSideBar() {
        mTopBar.setTitle("制作计划书");
        mTopBar.showRight(false);
        mTopBar.with(this);
        mTopBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        setTotalPremiumValue("0元");
        initBtnMakeProposal();
        initProposalProduct();
    }

    @Override
    public void initBtnMakeProposal() {
        mActionMakeProposal.setUnEnabledMessage("请完善计划书信息");
        mActionMakeProposal.setFragmentManager(getFrgManager());
        setMakeProposalEnabled(false);

        mActionMakeProposal.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /* 生成计划书*/
                ProposalEntity proposal = getProposal();
                if (checkBeforeMakeProposal(proposal)) {
                    Customer c = mApplicantView.getCustomer();
                    Customer customerApplicant = new Customer();
                    customerApplicant.setCustomerId(c.getCustomerId());
                    customerApplicant.setName(c.getName());
                    customerApplicant.setAge(c.getAge());
                    customerApplicant.setSex(c.getSex());
                    customerApplicant.setIsConfirm(c.getIsConfirm());
                    customerApplicant.setBirthday(c.getBirthday());
                    customerApplicant.setCareerCategory(c.getCareerCategory());
                    customerApplicant.setRelationWith(c.getRelationWith());
                    mPresenter.checkProposal(
                            mApplicantView.allowSaveToCustomerList(),
                            customerApplicant, originCustomerName,
                            proposal, true);
                }
            }
        });
    }

    @Override
    public void initApplicantView() {
        mApplicantView.supportFragmentManager(getSupportFragmentManager());
        mApplicantView.setOnApplicantChangedListener(new ApplicantView.OnApplicantChangedListener() {
            @Override
            public void onApplicantChanged() {
                //1. 更新投保人信息
                EventBus.getDefault().post(new ApplicantChangedEvent(mApplicantView.getApplicant()));
                //2. 找到是否有和投保人关系为“本人”的被保人，有的话，更新被保人信息与投保人一致
                InsuredView insuredViewWithRelationMyself = getMyselfInsuredView();
                if (insuredViewWithRelationMyself != null) {
                    updateInsuredByApplicant(insuredViewWithRelationMyself);
                    //2.1 先更新对应的insuredView？再全局更新exemptDao?
//                    doWhenInsuredChanged(insuredViewWithRelationMyself, insuredViewWithRelationMyself.getCorrespondingInsuranceView());
                }

                //3. 分别更新所有被保人信息，计算被保人的险种的值，这一步暂时没有添加，不添加可能会引起豁免显不更新的问题
                List<InsuredView> insuredViews = getAllInsuredViews();
                for (InsuredView item : insuredViews) {
                    doWhenInsuredChanged(item, item.getCorrespondingInsuranceView());
                }
            }
        });
    }

    //将投保人的信息拷贝给被保人，即被保人的信息与投保人一致
    private void updateInsuredByApplicant(InsuredView insuredView) {
        ApplicantEntity applicant = mApplicantView.getApplicant();
        if (applicant == null) {
            return;
        }
        InsuredEntity insured = insuredView.getInsured();
        insured.name = applicant.name;
        insured.sex = applicant.sex;
        insured.age = applicant.age;
        insured.birthday = applicant.birthday;

        insuredView.bindData(insured);
    }

    //在关系为本人的情况下，修改投保人信息会同时更新被保人信息
    private void updateInsured() {
        ApplicantEntity applicant = mApplicantView.getApplicant();
        if (applicant == null) {
            return;
        }
        InsuredEntity insured = mInsuredView.getInsured();
        insured.name = applicant.name;
        insured.sex = applicant.sex;
        insured.age = applicant.age;
        insured.birthday = applicant.birthday;

        mInsuredView.bindData(insured);
    }

    /**
     * 被保人信息变更时调用
     */
    private void doWhenInsuredChanged(InsuredView insuredView, InsuranceView insuranceView) {
        if (insuranceView == null) {
            return;
        }
        insuranceView.setInsuredPerson(insuredView.getInsured());
        //先更新每一个普通险种，更新完成后，再更新豁免险
        insuranceView.updateForCurrentInsuredPerson();
    }

    private InsuredView.CheckOtherRelationCallBack otherRelationCallBack = new InsuredView.CheckOtherRelationCallBack() {
        @Override
        public boolean checkOtherRelation(int relationCode) {
            return mPresenter.checkRelation(relationCode, getProposal());
        }
    };

    @Override
    public void initInsuredView() {
        mInsuredView.setCheckOtherRelationCallBack(otherRelationCallBack);
        mInsuredView.supportFragmentManager(getSupportFragmentManager());
        mInsuredView.setInsuredChangedListener(new InsuredView.onInsuredChangedListener() {
            @Override
            public void onInsuredChanged(int type) {
                EventBus.getDefault().post(new InsuredChangedEvent(mInsuredView, mInsuranceView, type));
            }
        });
    }

    @Override
    public void initInsuranceViews() {
        mInsuranceView.setFragmentManager(getSupportFragmentManager());
        mInsuranceView.setApplicantPerson(mApplicantView.getApplicant());
        mInsuranceView.setInsuredPerson(mInsuredView.getInsured());
        mInsuranceView.setOnProductAddListener(new InsuranceView.OnProductAddListener() {
            @Override
            public void addMainProduct() {
                /* 点击添加主险button回调函数*/
                InsuredEntity insured = mInsuredView.getInsured();
                ParamGetRisks param = new ParamGetRisks();
                param.age = insured == null ? Constant.PROPOSAL_AGE_DEFAULT : insured.age + "";
                param.sex = insured == null ? Constant.PROPOSAL_SEX_DEFAULT : insured.sex;
                param.profession = insured == null ? Constant.PROPOSAL_PROFESSION_DEFAULT : insured.profession;
                param.birthday = insured == null ? null : insured.birthday;
                mPresenter.addMainProduct(MakeProposalActivity.this, param);
                mainProductChangedForMore();
            }

            @Override
            public void addAttachProduct(ArrayList<String> exists) {
                EventBus.getDefault().post(new AddAttachProductEvent(mInsuranceView, exists));
            }

            @Override
            public void deleteMainProduct() {
                updateToudan(false, null);
                mainProductChangedForMore();
                updateBusinessConfig(null);
            }
        });

        mInsuranceView.setOnProductChangedListener(new InsuranceView.OnProductChangedListener() {
            @Override
            public void onProductChanged(InsuranceEntity data, int isMain, int action) {
                doOnProductChanged(mInsuranceView, data, isMain, action, false);
            }

            @Override
            public void onProductsChanged(List<InsuranceEntity> data) {
                doOnProductsChanged(mInsuranceView, data, false);
            }
        });
    }

    @Override
    public void initProposalProduct() {
        mTextProductInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
                if (mainInsuranceEntity == null) {
                    return;
                }
                showProgress("正在解析产品，请稍等");
                mPresenter.getAdditionalProducts(mainInsuranceEntity.productId, new GetAttachRiskListener() {
                    @Override
                    public void onResult(List<ResponseChanShuoItem> list) {
                        cancelProgress();
                        if (ArrayUtils.isEmpty(list)) {
                            showToast("当前没有产品，请先选择产品");
                            return;
                        }
                        mDialogProductInProposal = PickerHelper.showProductsInProposalDialog2(getFrgManager(), new ProductInProposalAdapter2(MakeProposalActivity.this, list));
                    }
                });
            }
        });
    }

    public interface GetAttachRiskListener {
        void onResult(List<ResponseChanShuoItem> list);
    }

    private ParamGetAttaches getRequestAttachesParam() {
        InsuranceEntity main_data = mInsuranceView.getMainProductData();

        if (main_data != null) {
            ParamGetAttaches param = new ParamGetAttaches();
            ApplicantEntity applicant = mApplicantView.getApplicant();
            InsuredEntity insured = mInsuredView.getInsured();
            param.mainProductId = main_data.productId;

            ParamGetAttaches.ApplicantBean applicantBean = new ParamGetAttaches.ApplicantBean();
            applicantBean.age = applicant == null ? Constant.PROPOSAL_AGE_DEFAULT : applicant.age + "";
            applicantBean.sex = applicant == null ? Constant.PROPOSAL_SEX_DEFAULT : applicant.sex;
            param.applicant = applicantBean;

            ParamGetAttaches.InsuredBean insuredBean = new ParamGetAttaches.InsuredBean();
            insuredBean.age = insured == null ? Constant.PROPOSAL_AGE_DEFAULT : DataUtils.formatRequestParamAge(insured.age + "", insured.birthday);
            insuredBean.sex = insured == null ? Constant.PROPOSAL_SEX_DEFAULT : insured.sex;
            insuredBean.profession = insured == null ? Constant.PROPOSAL_PROFESSION_DEFAULT : insured.profession;
            param.insured = insuredBean;
            return param;
        } else {
            return null;
        }
    }

    /**
     * 产品变更后的更新（添加、删除、修改）
     */
    public void updateWhenProductsChanged() {
        if (mInsuranceView.hasMain()) {
            setMakeProposalEnabled(true);
        } else {
            setMakeProposalEnabled(false);
        }
        // 变更完豁免险的保额与保费后，重新计算最大保费
        setTotalPremiumValue(DataUtils.parseIntValue(EBTDataFormat.formatNumber(getTotalPremiumAndCoverage()[0])) + "元");
    }

    @Subscribe
    public void onEvent(ExemptCompleteEvent e) {
        /*豁免险更新完毕*/
        if (e != null) {
            // 变更完豁免险的保额与保费后，重新计算最大保费
            if (e.refreshTotalPremium) {
                setTotalPremiumValue(DataUtils.parseIntValue(EBTDataFormat.formatNumber(getTotalPremiumAndCoverage()[0])) + "元");
            }
            // 校验
            if (e.needVerifyProposal) {
                mPresenter.checkProposal(false, null, null, getProposal(), false);
            }
        }
    }

    @Subscribe
    public void onEvent(DraftUpdateCompleteEvent event) {
        if (event != null) {
            // 草稿保存后，建议书列表刷新完毕，执行关闭当前页面
            finishActivity();
        }
        setDraftSaving(false);
    }

    @Override
    public FragmentManager getFrgManager() {
        return getSupportFragmentManager();
    }

    @Override
    public void addInsuranceView(InsuranceEntity data) {
        mInsuranceView.addRiskView(data);
    }

    @Override
    public void scrollToBottom() {
        mScrollView.post(() -> mScrollView.fullScroll(ScrollView.FOCUS_DOWN));
    }

    @Override
    public void checkProposalMakeAllowed() {
        if (!mPresenter.isLogined()) {
            UIHelper.makeToast(this, getResources().getString(R.string.pro_need_login));
            finish();
            return;
        }
        if (!mPresenter.isCompanyRegistered()) {
            EBTConfirmDialogWithTitle confirm = new EBTConfirmDialogWithTitle();
            confirm.setMessage(getResources().getString(R.string.no_company_register));
            confirm.setPositiveButton("确定", v -> {
                confirm.dismiss();
                finish();
            });
            confirm.setNegativeButton("取消", v -> {
                confirm.dismiss();
                finish();
            });
            confirm.show(getFrgManager(), "preventMakeProposal");
            return;
        }
    }

    @Override
    public void showToast(String msg) {
        UIHelper.makeToast(this, msg);
    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void finishCustomActivity() {
        finish();
        if (WebBaseActivity.INSTANCE != null) {
            WebBaseActivity.INSTANCE.finish();
        }
    }

    @Override
    public void checkToProposalList() {
        if (finishToProposalList) {
            Intent intent = new Intent(this, ActProposalList.class);
            startActivity(intent);
        }
    }

    @Override
    public void gotoProposalDetail(ArgProposalDetail arg) {
        ProposalUtils.previewProposal(this, arg);
    }

    @Override
    public ProposalEntity getProposal() {
        ProposalEntity entity = new ProposalEntity();
        // ID
        if (mArg != null && !TextUtils.isEmpty(mArg.proposalId)) {
            entity.pickNum = mArg.proposalId;
        } else {
            entity.pickNum = UUID.randomUUID().toString();
        }
        InsuranceEntity dataMain = getMain();

        if (dataMain == null) {
            entity.proposalName = "";
            entity.description = "";
            entity.thumbnail = "";
        } else {
            entity.proposalName = dataMain.productName;
            entity.description = dataMain.description;
            entity.thumbnail = dataMain.thumbnail;
        }
        // 总保额 & 总保费
        double[] total = getTotalPremiumAndCoverage();
        if (total == null || total.length < 2) {
            entity.totalCoverage = 0;
            entity.totalPremium = 0;
        } else {
            entity.totalPremium = total[0];
            entity.totalCoverage = total[1];
        }
        // 投保人
        entity.applicant = mApplicantView.getApplicant();
        // 被保人 & 保险
        InsuredEntity insured = mInsuredView.getInsured();
        if (insured != null) {
            if (insured.relation == 0 && entity.applicant != null) {
                /* 如果是本人，则初始化被保人的基本信息为投保人信息*/
                insured.clientAccountId = entity.applicant.clientAccountId;
                insured.name = entity.applicant.name;
                insured.sex = entity.applicant.sex;
                insured.age = entity.applicant.age;
                insured.birthday = entity.applicant.birthday;
            }
            insured.risk = mInsuranceView.getProductsData();
        }
        List<InsuredEntity> insuredList = new ArrayList<>();
        insuredList.add(insured);

        List<InsuredEntity> moreInsuredEntityList = getMoreInsuredList();
        if (moreInsuredEntityList != null && moreInsuredEntityList.size() > 0) {
            for (InsuredEntity insuredEntity : moreInsuredEntityList) {
                if (insuredEntity.relation == 0 && entity.applicant != null) {
                    /* 如果是本人，则初始化被保人的基本信息为投保人信息*/
                    insuredEntity.clientAccountId = entity.applicant.clientAccountId;
                    insuredEntity.name = entity.applicant.name;
                    insuredEntity.sex = entity.applicant.sex;
                    insuredEntity.age = entity.applicant.age;
                    insuredEntity.birthday = entity.applicant.birthday;
                }
                insuredList.add(insuredEntity);
            }
        }
        entity.insured = insuredList;
        entity.businessConfig = getBusinessConfigFromInsuranceView();
        entity.shouldSaveClient = mApplicantView.allowSaveToCustomerList() ? 1 : 0;
        return entity;
    }

    private BusinessConfig getBusinessConfigFromInsuranceView() {
        InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
        if (mainInsuranceEntity != null) {
            BusinessConfig businessConfig = mainInsuranceEntity.getBusinessConfig();
            return businessConfig;
        }
        return null;
    }


    private List<InsuredEntity> getMoreInsuredList() {
        List<InsuredEntity> list = new ArrayList<>();
        if (moreInsuredAndInsuranceViewContainer != null && moreInsuredAndInsuranceViewContainer.getChildCount() > 0) {
            int childCount = moreInsuredAndInsuranceViewContainer.getChildCount();
            for (int i = 0; i < childCount; i++) {
                InsuredAndInsuranceView iv = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(i);
                InsuredEntity insuredEntity = getInsuredEntityFromInsuredAndInsuranceView(iv);
                if (insuredEntity != null) {
                    list.add(insuredEntity);
                }
            }
            return list;
        } else {
            return null;
        }
    }

    private InsuredEntity getInsuredEntityFromInsuredAndInsuranceView(InsuredAndInsuranceView view) {
        return view.getInsuredEntity();
    }

    @Override
    public ApplicantEntity getApplicant() {
        return mApplicantView.getApplicant();
    }

    @Override
    public InsuredEntity getInsured() {
        return mInsuredView.getInsured();
    }

    @Override
    public InsuranceEntity getMain() {
        return mInsuranceView.getMainProductData();
    }

    //主险选择返回
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MainChooseEvent ev) {
        if (ev != null && !mInsuranceView.hasMain()) {
            mPresenter.addAdditionalViewAfterChoose(ev.list);
//            updateToudanByToudanInfo(ev.touDanInfo);
            updateToudanByProductId(ev.touDanInfo.productId);
        }
    }

    private void updateToudanByToudanInfo(TouDanInfo info) {
        if (info != null && info.isOpenInsurance != null && info.isOpenInsurance > 0) {
            updateToudan(true, info.insuranceUrl);
        } else {
            updateToudan(false, null);
        }
    }

    private void updateToudan(boolean show, String url) {
        if (show) {
            mActionOnlineToudan.setVisibility(View.VISIBLE);
            mActionOnlineToudan.setTag(url);
        } else {
            mActionOnlineToudan.setVisibility(View.GONE);
        }

    }

    //选择附加险返回
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AddAttachProductEvent event) {
        ArrayList<String> allAddtionIds = new ArrayList<>();
        ArrayList<String> firstAdditionIds = mInsuranceView.getExistsAdditionalIds();
        ArrayList<String> otherAdditionIds = getMoreInsuredAdditionalIds();
        if (firstAdditionIds != null) {
            allAddtionIds.addAll(firstAdditionIds);
        }
        if (otherAdditionIds != null) {
            allAddtionIds.addAll(otherAdditionIds);
        }
        event.exists = allAddtionIds;
        doAddAttachProductEvent(event);
    }

    /**
     * 豁免险重置后，刷新总保费
     *
     * @param ev
     */
    @Subscribe
    public void onEvent(ExemptResetEvent ev) {
        if (ev != null) {
            setTotalPremiumValue(DataUtils.parseIntValue(EBTDataFormat.formatNumber(getTotalPremiumAndCoverage()[0])) + "元");
        }
    }

    public void onSaveProposalDraft() {
        if (isProposalDraftSaving) {
            return;
        }
        if (checkDraftSame()) {
            //TODO 如果两者相同，直接退出
            finishActivity();
            return;
        }

        EBTDialog mLoginOutConfirmDialog = new EBTDialog();
        mLoginOutConfirmDialog.setMessage("是否需要保存计划书草稿，以便于下次继续编辑？");
        mLoginOutConfirmDialog.setRightButton("保存", v -> {
            setDraftSaving(true);
            mPresenter.saveToProposalDraft(getProposal());
        });
        mLoginOutConfirmDialog.setLeftButton("不保存", v -> {
            mLoginOutConfirmDialog.dismiss();
            finishActivity();
        });
        mLoginOutConfirmDialog.show(getSupportFragmentManager(), getClass().getSimpleName());

    }

    @Override
    public void onBackPressed() {
        if (mInsuranceView.hasMain()) {
            onSaveProposalDraft();
        } else {
            finishActivity();
        }
    }

    @Override
    public void showProgress(String msg) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (!isFinishing() && !isDestroyed()) {
                showProgressDialog();
            }
        } else {
            if (!isFinishing()) {
                showProgressDialog();
            }
        }
    }

    private void showProgressDialog() {
        mProgressDialog = getEBTProgressDialog();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                EventBus.getDefault().post(new CancelCalculating());
            }
        });
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    private EBTProgressDialog getEBTProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new EBTProgressDialog(this);
        }
        return mProgressDialog;
    }

    @Override
    public void cancelProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

    @Override
    public void setOriginCustomerName(String name) {
        this.originCustomerName = name;
    }

    @Override
    public void showTipDialog(String tip) {
        mContentView.postDelayed(new Runnable() {
            @Override
            public void run() {
                PickerHelper.tip(tip).show(getFrgManager(), "ProposalTip");
            }
        }, 100);
    }

    void updateProductShown() {
        int childCount = mInsuranceView.getViewCount();
        if (childCount == 0) {
            mProductSeparator.setVisibility(View.GONE);
            mTextProductInfo.setVisibility(View.GONE);
        } else {
            mProductSeparator.setVisibility(View.VISIBLE);
            mTextProductInfo.setVisibility(View.VISIBLE);
        }
    }

    //添加更多被保人
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AddMoreInsuredEvent event) {
        if (!canAddMore()) {
            Toast.makeText(this, "不能添加更多的被保人了", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            InsuredAndInsuranceView insuredAndInsuranceView = new InsuredAndInsuranceView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
            if (mainInsuranceEntity != null) {
                insuredAndInsuranceView.updateDefaultBusinessConfig(mainInsuranceEntity.getBusinessConfig());
            }
            insuredAndInsuranceView.setCorrespondingApplicantView(mApplicantView);
            insuredAndInsuranceView.setOtherRelationCallBack(otherRelationCallBack);
            moreInsuredAndInsuranceViewContainer.addView(insuredAndInsuranceView, lp);
            insuredAndInsuranceView.updateTitleByIndex(moreInsuredAndInsuranceViewContainer.getChildCount() - 1);

            updateMoreInsuredAndInsuranceViewState();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean canAddMore() {
        int moreCount = moreInsuredAndInsuranceViewContainer.getChildCount();
        InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
        if (mainInsuranceEntity != null) {
            BusinessConfig businessConfig = mainInsuranceEntity.getBusinessConfig();
            if (businessConfig != null && businessConfig.proposal_supportMultipleInsured > 0
                    && businessConfig.proposal_maxInsured > moreCount) {
                return true;
            }
        }
        return false;
    }

    private void updateMoreInsuredAndInsuranceViewState() {
        if (moreInsuredAndInsuranceViewContainer.getChildCount() > 0) {
            moreInsuredAndInsuranceViewContainer.setVisibility(View.VISIBLE);
        } else {
            moreInsuredAndInsuranceViewContainer.setVisibility(View.GONE);
        }
    }

    //删除某个 更多被保人
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeleteMoreInsuredEvent event) {
        if (event != null && event.clickedView != null) {
            View v = event.clickedView;
            while (v.getParent() != null) {
                View vp = (View) v.getParent();
                if (vp instanceof InsuredAndInsuranceView) {
                    popConfirmDialog(vp);
                    break;
                }
                v = (View) v.getParent();
            }
        }
    }

    private void popConfirmDialog(final View vp) {
        ConfirmDialog mDeleteConfirmDialog = new ConfirmDialog(this);
        mDeleteConfirmDialog.setMessage("请确认是否删除该被保人及其附加险？");
        mDeleteConfirmDialog.setPositiveButton("删除", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDeleteConfirmDialog.dismiss();
                moreInsuredAndInsuranceViewContainer.removeView(vp);
            }
        });
        mDeleteConfirmDialog.show();
    }

    private void mainProductChangedForMore() {
        moreInsuredAndInsuranceViewContainer.removeAllViews();
        moreInsuredView.setVisibility(View.GONE);
    }

    //添加一个产品
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ProductChangedEvent event) {
        InsuranceView insuranceView = event.insuranceView;
        event.insuranceView = null;
        doOnProductChanged(insuranceView, event.data, event.isMain, event.action, event.fromMore);
    }

    //添加多个产品
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ProductsChangedEvent event) {
        InsuranceView insuranceView = event.insuranceView;
        event.insuranceView = null;
        doOnProductsChanged(insuranceView, event.data, event.fromMore);
    }

    //被保人信息改变，无论被保人是第几被保人
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(InsuredChangedEvent event) {
        doWhenInsuredChanged(event.insuredView, event.insuranceView);
    }

    private void doAddAttachProductEvent(AddAttachProductEvent event) {
        /* 添加附加险*/
        InsuranceEntity mainInsuranceEntity = mInsuranceView.getMainProductData();
        ApplicantEntity applicantEntity = mApplicantView.getApplicant();
        if (mainInsuranceEntity != null && applicantEntity != null) {
            InsuredEntity insured = mInsuredView.getInsured();
            ParamGetAttaches param = new ParamGetAttaches();
            param.mainProductId = mainInsuranceEntity.productId;

            ParamGetAttaches.ApplicantBean applicantBean = new ParamGetAttaches.ApplicantBean();
            applicantBean.age = applicantEntity == null ? Constant.PROPOSAL_AGE_DEFAULT : applicantEntity.age + "";
            applicantBean.sex = applicantEntity == null ? Constant.PROPOSAL_SEX_DEFAULT : applicantEntity.sex;
            param.applicant = applicantBean;

            ParamGetAttaches.InsuredBean insuredBean = new ParamGetAttaches.InsuredBean();
            insuredBean.age = insured == null ? Constant.PROPOSAL_AGE_DEFAULT : DataUtils.formatRequestParamAge(insured.age + "", insured.birthday);
            insuredBean.sex = insured == null ? Constant.PROPOSAL_SEX_DEFAULT : insured.sex;
            insuredBean.profession = insured == null ? Constant.PROPOSAL_PROFESSION_DEFAULT : insured.profession;
            param.insured = insuredBean;

            AdditionalRiskChooseDialog dialog = AdditionalRiskChooseDialog.newInstance(event.exists, param);
            dialog.addProductChooseListener(new AdditionalRiskChooseDialog.onAdditionalRiskChooseListener() {
                @Override
                public void onAdditionalProductChoose(List<InsuranceEntity> additionalRiskList) {
                    dialog.dismiss();
                    if (additionalRiskList != null && additionalRiskList.size() > 0) {
                        event.insuranceView.addRiskViews(additionalRiskList);
                    }
                }
            });
            dialog.show(getSupportFragmentManager(), "chooseAttachProduct");
        }
    }

    public void doOnProductChanged(InsuranceView insuranceView, InsuranceEntity data, int isMain, int action, boolean fromMore) {
        updateWhenProductsChanged();
        updateProductShown();
        boolean hasExemptUpdated = false;
        if (data != null) {
            if (isMain == PRODUCT_ATTATCH && (action == ACTION_PRODUCT_ADD || action == ACTION_PRODUCT_DELETE || action == ACTION_PRODUCT_EDIT)) {
                // 变更附加险时执行
                if (data.riskType == RISK_TYPE_COMMON) {
                    // 更改普通附加险后
                    hasExemptUpdated = true;
                    mExemptDao.updateExemptViewAfterModifyCommon(data, mApplicantView.getCustomer(), mInsuredView.getCustomer());
                } else if (data.riskType == RISK_TYPE_EXEMPT && action == ACTION_PRODUCT_ADD) {
                    // 添加豁免附加险后
                    hasExemptUpdated = true;
                    mExemptDao.updateExemptViewAfterAddExempt(mApplicantView.getCustomer(), mInsuredView.getCustomer());
                }
            }

            if ((isMain == PRODUCT_MAIN || isMain == 2) && action == ACTION_PRODUCT_EDIT) {
                // 修改主险时，重置豁免险
                hasExemptUpdated = true;
                mExemptDao.updateExemptViewAfterModifyCommon(data, mApplicantView.getCustomer(), mInsuredView.getCustomer());
            }

            if (!hasExemptUpdated) {
                mPresenter.checkProposal(false, null, null, getProposal(), false);
            }
        }
    }

    public List<InsuredView> getMoreInsuredViews() {
        List<InsuredView> ret = new ArrayList<>();
        if (moreInsuredAndInsuranceViewContainer == null) {
            return ret;
        }
        int childCount = moreInsuredAndInsuranceViewContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            InsuredAndInsuranceView iv = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(i);
            ret.add(iv.getInsuredView());
        }
        return ret;
    }

    public List<InsuredView> getAllInsuredViews() {
        List<InsuredView> ret = new ArrayList<>();
        ret.add(mInsuredView);
        ret.addAll(getMoreInsuredViews());
        return ret;
    }


    public void doOnProductsChanged(InsuranceView insuranceView, List<InsuranceEntity> data, boolean fromMore) {
        updateWhenProductsChanged();
        updateProductShown();
        if (data != null && data.size() > 0) {
            mExemptDao.updateExemptViewAfterModifyCommon(data, mApplicantView.getCustomer(), mInsuredView.getCustomer());
        }
    }

    public InsuredView getMyselfInsuredView() {
        //第一被保人
        if (mInsuredView != null) {
            int relation = mInsuredView.getRelation();
            if (relation == 0) {
                return mInsuredView;
            }
        }
        //获取多被保人的其它InsuredView
        List<InsuredView> insuredViews = getMoreInsuredViews();
        for (InsuredView view : insuredViews) {
            if (view != null && view.getRelation() == 0) {
                return view;
            }
        }
        return null;
    }

    /**
     * 检测产品投保选项是否匹配性别、年龄、职业类别
     *
     * @return
     */
    @Override
    public boolean checkProductOption() {
        boolean retCheckBoolean = true;
        ArrayList<InsuranceCellView> cellViews = mInsuranceView.getInsuranceCellViews();
        for (InsuranceCellView cellView : cellViews) {
            ArrayList<Object> retCellCheck = cellView.checkIfMatchCondition();
            if (!(Boolean) retCellCheck.get(0)) {
                retCheckBoolean = false;
                showTipDialog(String.valueOf(retCellCheck.get(1)));
                break;
            }
        }
        if (retCheckBoolean) {
            if (hasMoreInsuredAndInsuranceView()) {
                int childCount = moreInsuredAndInsuranceViewContainer.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    InsuredAndInsuranceView iv = (InsuredAndInsuranceView) moreInsuredAndInsuranceViewContainer.getChildAt(i);
                    ArrayList<Object> listCellCheck = iv.checkProductOption();
                    if (listCellCheck != null) {
                        if (!(Boolean) listCellCheck.get(0)) {
                            retCheckBoolean = false;
                            showTipDialog(String.valueOf(listCellCheck.get(1)));
                            break;
                        }
                    }
                }
            }
        }
        return retCheckBoolean;
    }

    @Override
    public boolean hasMoreInsuredAndInsuranceView() {
        if (moreInsuredAndInsuranceViewContainer != null && moreInsuredAndInsuranceViewContainer.getChildCount() > 0 && moreInsuredAndInsuranceViewContainer.getVisibility() == View.VISIBLE) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
        if (empty || net_slow || no_net) {
            mEmptyView.setVisibility(View.VISIBLE);
            mScrollView.setVisibility(View.GONE);
            mBottomBar.setVisibility(View.GONE);
            mEmptyContentContainer.setVisibility(empty ? View.VISIBLE : View.GONE);
            noNetContainer.setVisibility(no_net ? View.VISIBLE : View.GONE);
            netSlowContainer.setVisibility(net_slow ? View.VISIBLE : View.GONE);
        } else {
            mEmptyView.setVisibility(View.GONE);
            mScrollView.setVisibility(View.VISIBLE);
            mBottomBar.setVisibility(View.VISIBLE);
        }

    }

    @OnClick({R.id.load_refresh, R.id.load_refresh_net})
    public void onRefreshClicked(View v) {
        //默认新建不需要联网判断
        if (NetUtils.isNetworkConnected(this) || (mArg != null && mArg.flag == Flag_Default)) {
            initByFlag();
        } else {
            showToast(getResources().getString(R.string.network_fail));
            showEmpty(false, true, false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UpdaterFailEvent event) {
        List<InsuredView> list = getAllInsuredViews();
        List<InsuranceView> listInsuranceView = new ArrayList<>();
        for (InsuredView item : list) {
            listInsuranceView.add(item.getCorrespondingInsuranceView());
        }
        for (InsuranceView item : listInsuranceView) {
            InsuranceCellViewUpdater updater = item.getInsuranceCellViewUpdater();
            if (updater != null) {
                updater.stopWebViewLoading();
            }
        }
        Toast.makeText(this, getString(R.string.update_premium_fail), Toast.LENGTH_LONG).show();
    }

    private void updateToudanByProductId(int productId) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getResponseTouDan(productId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBodyBase<ResponseTouDan>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(ResponseBodyBase<ResponseTouDan> value) {
                        //获取限额提示
                        mPresenter.getProductProperties(productId);
                        if (value != null && value.data != null) {
                            updateToudanByToudanInfo(new TouDanInfo(value.data.isOpenInsurance, value.data.insuranceUrl, value.data.productId));
                        } else {
                            updateToudanByToudanInfo(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                    }
                });


    }

}